package com.example.customview.silder

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

object JsonUtil {
    private var gson: Gson? = null

    fun getGson(): Gson {
        if (gson == null) {
            gson = GsonBuilder().create()
        }
        return gson!!
    }

    @JvmStatic
    @Throws(JsonSyntaxException::class)
    fun <T> parseJsonToObject(json: String?, classOfT: Type): T {
        return getGson().fromJson(json, classOfT)
    }
    @JvmStatic
    @Throws(JsonSyntaxException::class)
    fun <T> parseJsonToObject(json: String?, classOfT: Class<T>): T {
        return getGson().fromJson(json, classOfT)
    }

    @JvmStatic
    fun <T> objectToJson(t: T?): String {
        return getGson().toJson(t)
    }

    inline fun <reified T> parseJsonToObject(json: String?): T {
        return getGson().fromJson(json, object: TypeToken<T>(){}.type)
    }

    @JvmStatic
    @Throws(JsonSyntaxException::class)
    fun <T> parse(jsonStr: String?, cl: Class<T>?): T? {
        var obj: T? = null
        obj = getGson().fromJson(jsonStr, cl)
        return obj
    }

}